<?php

namespace src;

use src\interfaces\IRouteCollectionInterface;
use \Countable;
use \IteratorAggregate;
use ArrayIterator;

class RouteCollection implements Countable, IteratorAggregate, IRouteCollectionInterface
{
    protected $routes = [];
    protected $allRoutes = [];

    public function add(Route $route)
    {
        foreach ($route->methods() as $method){
            $this->routes[$method][$route->uri()] = $route;
            $this->allRoutes[$method][$route->uri()] = $route;
        }
        return $this;
    }

    public function getIterator()
    {
        return new ArrayIterator($this->getRoutes());
    }

    public function count()
    {
        return count($this->getRoutes());
    }

    public function match(Request $request)
    {
        $method = $request->getMethod();
        /**
         * @var Route $route
         */
        foreach ($this->routes[$method] as $route){
            if ($route->uri() == $request->getUri()){
                return $route;
            }
        }
        return  null;
    }

    public function get($method = null)
    {
        // TODO: Implement get() method.
    }

    public function hasNamedRoute($name)
    {
        // TODO: Implement hasNamedRoute() method.
    }

    public function getByName($name)
    {
        // TODO: Implement getByName() method.
    }

    public function getByAction($action)
    {
    }

    public function getRoutes()
    {
        return array_values($this->allRoutes);
    }
}